package org.midy.infrastructure.tools;

import java.nio.channels.*;
import java.util.Set;

public class CloseHandler {

    public static Selector closeSelector(Selector selector) {
        if( selector != null && selector.isOpen()) {
            try {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                if(selectionKeys != null && !selectionKeys.isEmpty() ) {
                    for(SelectionKey selectionKey : selectionKeys) {
                        selectionKey.cancel();
                    }
                }
                selector.close();
            } catch (Exception ce) {
                Logger.debug("关闭 Selector 失败：%s", ce.getMessage());
            }
        }
        return selector;
    }

    public static ServerSocketChannel closeServerSocketChannel(ServerSocketChannel serverSocketChannel) {
        if(serverSocketChannel != null && serverSocketChannel.isOpen()) {
            try {
                serverSocketChannel.close();
            } catch (Exception e) {
                Logger.debug("关闭 ServerSocketChannel 失败：%s", e.getMessage());
            }
        }
        return null;
    }

    public static void closeSocketChannel(SocketChannel socketChannel) {
        if(socketChannel != null && socketChannel.isOpen()) {
            try {
                socketChannel.close();
            } catch (Exception e) {
                String address = "";
                try {
                    address = socketChannel.getRemoteAddress().toString();
                } catch (Throwable t) {
                    Logger.warn("获取远程 IP:PORT 失败");
                }
                Logger.error("关闭 ServerSocketChannel IP:PORT["+ address +"] 出现未知失败：%s", e);
            }
        }
    }

    public static SelectableChannel closeSelectionKey(SelectionKey selectionKey) {
        SelectableChannel selectableChannel = selectionKey.channel();
        if(selectionKey != null && selectionKey.isValid()) {
            try {
                SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
                if(socketChannel != null && socketChannel.isOpen()) {
                    socketChannel.close();
                }
            } catch (Exception e) {
                Logger.debug("关闭 selectableChannel 失败：%s", e.getMessage());
            }

            try {
                selectionKey.cancel();
            } catch (Exception e) {
                Logger.debug("关闭 ServerSocketChannel 失败：%s", e.getMessage());
            }
        }
        return selectableChannel;
    }
}
